from PIL import Image, ImageDraw, ImageFont
import os
import math
import platform

# --- 配置 ---
SYSTEM = platform.system()
if SYSTEM == "Windows":
    FONT_PATH = "C:/Windows/Fonts/simhei.ttf"
elif SYSTEM == "Darwin":
    FONT_PATH = "/Library/Fonts/Songti.ttc"
else:
    FONT_PATH = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"

INPUT_DIR = "../add_text/pomeranian_colors_annotated_final"
OUTPUT_DIR = "../add_text/pomeranian_visual_reports_final"
ZIP_PATH = "../add_text/pomeranian_visual_reports_final/pomeranian_visual_reports_final.zip"

os.makedirs(OUTPUT_DIR, exist_ok=True)

# 报表尺寸 (3:4 比例)
WIDTH, HEIGHT = 768, 1024
BACKGROUND_COLOR = (255, 255, 255)
TEXT_COLOR = (0, 0, 0)


# --- 辅助函数 ---
def get_text_size(draw, text, font):
    bbox = draw.textbbox((0, 0), text, font=font)
    return bbox[2] - bbox[0], bbox[3] - bbox[1]


# --- 主生成函数 ---
def generate_visual_report():
    all_files = sorted([f for f in os.listdir(INPUT_DIR) if f.endswith('.png')])
    total_colors = len(all_files)

    # 每张报告包含 2 种毛色 (1×2 上下布局)
    colors_per_report = 2
    num_reports = math.ceil(total_colors / colors_per_report)

    try:
        FONT_TITLE = ImageFont.truetype(FONT_PATH, 36)
    except IOError:
        FONT_TITLE = ImageFont.load_default()

    # 预留顶部标题空间
    title_area_height = 80
    image_area_height = HEIGHT - title_area_height

    # 1×2 网格：每张小图宽度为报表宽度，高度为 image_area_height 的一半
    grid_width = WIDTH
    grid_height = image_area_height // 2

    for i in range(num_reports):
        start_index = i * colors_per_report
        end_index = min((i + 1) * colors_per_report, total_colors)
        current_files = all_files[start_index:end_index]

        report_img = Image.new('RGB', (WIDTH, HEIGHT), color=BACKGROUND_COLOR)
        draw = ImageDraw.Draw(report_img)

        # --- 标题 ---
        title_text = f"博美犬25种毛色图鉴 (第 {i + 1} 部分 / 共 {num_reports} 部分)"
        title_width, title_height = get_text_size(draw, title_text, FONT_TITLE)
        title_x = (WIDTH - title_width) // 2
        title_y = (title_area_height - title_height) // 2
        draw.text((title_x, title_y), title_text, font=FONT_TITLE, fill=TEXT_COLOR)

        draw.line([(0, title_area_height), (WIDTH, title_area_height)], fill=(200, 200, 200), width=2)

        # --- 图像网格 ---
        for j, file_name in enumerate(current_files):
            try:
                # 确定垂直位置（第1张在上方，第2张在下方）
                y_offset = j * grid_height + title_area_height

                # 打开并调整小图尺寸
                input_path = os.path.join(INPUT_DIR, file_name)
                small_img = Image.open(input_path).convert("RGB")
                small_img = small_img.resize((grid_width, grid_height))

                # 粘贴到报告图片上
                report_img.paste(small_img, (0, y_offset))

                # 绘制水平分隔线（仅在有两张图时绘制）
                if j == 0 and len(current_files) == 2:
                    draw.line([(0, y_offset + grid_height), (WIDTH, y_offset + grid_height)],
                              fill=(200, 200, 200), width=1)

            except Exception as e:
                print(f"处理文件 {file_name} 时发生错误: {e}")

        # 保存报告图片
        output_file_name = f"Pomeranian_Visual_Report_Final_{i + 1}_of_{num_reports}.png"
        report_img.save(os.path.join(OUTPUT_DIR, output_file_name))
        print(f"成功生成最终视觉报告: {output_file_name}")


# --- 执行生成和打包 ---
generate_visual_report()

import zipfile
with zipfile.ZipFile(ZIP_PATH, 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, _, files in os.walk(OUTPUT_DIR):
        for file in files:
            zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), OUTPUT_DIR))
print(f"报告已打包至: {ZIP_PATH}")